<template>
  <div class="home-container">
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 智能助手聊天区域 -->
      <div class="chat-section">
        <div class="chat-header">
          <el-button 
            circle 
            @click="goBack"
            class="back-btn"
          >
            <img :src="backIcon" alt="退出" class="back-icon" />
          </el-button>
          
          <h2 class="chat-title">智能助手</h2>
          
          <el-button 
            circle 
            @click="showMenu"
            class="menu-btn"
          >
            <img :src="moreIcon" alt="更多" class="menu-icon" />
          </el-button>
        </div>

        <!-- 聊天消息区域 -->
        <div class="chat-messages" ref="messageContainer">
          <div 
            v-for="message in messages" 
            :key="message.id" 
            :class="['message', message.type]"
          >
            <div class="message-avatar">
              <el-avatar 
                :size="40"
                :src="message.type === 'assistant' ? assistantAvatar : user?.avatar || userAvatar"
                :icon="message.type === 'assistant' ? 'ChatDotRound' : 'User'"
              />
            </div>
            <div class="message-content">
              <div class="message-bubble">
                {{ message.content }}
              </div>
              <div class="message-time">
                {{ formatTime(message.timestamp) }}
              </div>
            </div>
          </div>
          
          <!-- 加载状态 -->
          <div v-if="loading" class="message assistant">
            <div class="message-avatar">
              <el-avatar 
                :size="40"
                :src="assistantAvatar"
                icon="ChatDotRound"
              />
            </div>
            <div class="message-content">
              <div class="message-bubble loading">
                <span class="loading-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </span>
              </div>
            </div>
          </div>
        </div>



        <!-- 输入区域 -->
        <div class="input-section">
          <div class="input-container">
            <el-input
              v-model="inputMessage"
              placeholder="请输入问题"
              :disabled="loading"
              @keyup.enter="sendMessage"
              class="message-input"
            >
              <template #append>
                <el-button 
                  @click="startVoiceInput"
                  :disabled="loading"
                  class="voice-btn"
                >
                  <img :src="speakIcon" alt="语音" class="voice-icon" />
                </el-button>
              </template>
            </el-input>
            <el-button 
              type="primary"
              @click="sendMessage"
              :disabled="!inputMessage.trim() || loading"
              class="send-btn"
            >
              <img :src="sendIcon" alt="发送" class="send-icon" />
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 左侧悬浮快捷操作按钮 -->
    <div class="floating-quick-actions" v-if="showQuickActions">
      <div 
        v-for="action in quickActions" 
        :key="action.id"
        class="quick-action-item"
        @click="handleQuickAction(action)"
      >
        <span class="quick-action-text">{{ action.title }}</span>
      </div>
    </div>

    <!-- 右侧悬浮功能按钮 -->
    <div class="floating-features">
      <div 
        class="floating-feature-btn"
        @click="goToNavigation"
      >
        <img :src="venueIcon1" alt="场馆图标" class="feature-icon-above" />
        <img :src="venueIcon" alt="场馆" class="feature-img" />
      </div>

      <div 
        class="floating-feature-btn"
        @click="goToPerformances"
      >
        <img :src="artistIcon2" alt="艺人图标" class="feature-icon-above" />
        <img :src="artistIcon" alt="艺人" class="feature-img" />
      </div>

      <div 
        class="floating-feature-btn"
        @click="goToInteraction"
      >
        <img :src="voteIcon3" alt="投票图标" class="feature-icon-above" />
        <img :src="voteIcon" alt="投票" class="feature-img" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getUnreadNotificationCount } from '@/api/notification'
import { sendMessageStream, getQuickActions } from '@/api/difyAI'
// import { sendMessageStream, getQuickActions } from '@/api/assistant'
import type { ChatMessage, QuickAction } from '@/types'
import dayjs from '@/utils/dayjs'

// 导入图片资源
import assistantAvatar from '@/assets/images/头像1.png'
import userAvatar from '@/assets/images/头像2.png'
import venueIcon from '@/assets/images/場館.png'
import artistIcon from '@/assets/images/藝人.png'
import voteIcon from '@/assets/images/投票.png'
import venueIcon1 from '@/assets/images/场馆icon1.png'
import artistIcon2 from '@/assets/images/艺人icon2.png'
import voteIcon3 from '@/assets/images/投票icon3.png'
import moreIcon from '@/assets/images/more.png'
import speakIcon from '@/assets/images/speak.png'
import sendIcon from '@/assets/images/send.png'
import backIcon from '@/assets/images/BACK.png'

// 响应式数据
const unreadCount = ref(0)
const loading = ref(false)
const inputMessage = ref('')
const messages = reactive<ChatMessage[]>([])
const showQuickActions = ref(true)
const menuVisible = ref(false)
const messageContainer = ref<HTMLElement>()

// 快捷操作
const quickActions = ref<QuickAction[]>([
  { id: '1', title: '我想投票', action: 'vote', icon: 'Star' },
  { id: '2', title: '今天天气如何?', action: 'weather', icon: 'Sunny' },
  { id: '3', title: '最火的艺人是哪位', action: 'artist', icon: 'User' },
  { id: '4', title: '演出时间安排', action: 'schedule', icon: 'Calendar' },
  { id: '5', title: '场地设施查询', action: 'facility', icon: 'Location' },
  { id: '6', title: '冷知识分享', action: 'trivia', icon: 'QuestionFilled' }
])

// 获取路由和用户store
const router = useRouter()
const userStore = useUserStore()

// 计算属性
const user = computed(() => userStore.user)

// 页面跳转方法
const goBack = () => router.go(-1)
const goToNavigation = () => router.push('/navigation')
const goToPerformances = () => router.push('/performances')
const goToInteraction = () => router.push('/interaction')
const goToProfile = () => router.push('/profile')
const goToSearch = () => router.push('/search')
const goToNotifications = () => router.push('/notifications')
const goToArtists = () => router.push('/artists')

// 获取未读通知数量
const fetchUnreadCount = async () => {
  try {
    const response = await getUnreadNotificationCount()
    const responseData = response.data as any
    unreadCount.value = responseData.data.count
  } catch (error) {
    console.error('获取未读通知数量失败:', error)
  }
}

// 显示菜单
const showMenu = () => {
  menuVisible.value = true
}

// 发送消息 - 流式响应
const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) return
  
  // 检查用户是否已登录
  if (!userStore.isLoggedIn) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  
  const userMessage: ChatMessage = {
    id: Date.now().toString(),
    type: 'user',
    content: inputMessage.value,
    timestamp: new Date().toISOString()
  }
  
  messages.push(userMessage)
  const messageToSend = inputMessage.value
  inputMessage.value = ''
  
  await nextTick()
  scrollToBottom()
  
  loading.value = true
  
  // 创建助手消息占位符
  const assistantMessage: ChatMessage = {
    id: (Date.now() + 1).toString(),
    type: 'assistant',
    content: '',
    timestamp: new Date().toISOString()
  }
  
  // 使用流式API
  const cancelStream = sendMessageStream(
    {
      message: messageToSend,
      inputs: {
        query: messageToSend
      }
    },
    (chunk) => {
      // 处理流式响应块
      if (chunk.type === 'start') {
        loading.value = false
  
  messages.push(assistantMessage)
  nextTick(() => scrollToBottom())
        loading.value = true
      } else if (chunk.type === 'chunk') {
        loading.value = false
        // 直接追加内容，不使用光标
        assistantMessage.content += chunk.message
        // 强制触发响应式更新
        messages.splice(0, messages.length, ...messages)
        nextTick(() => scrollToBottom())
        loading.value = true
      } else if (chunk.type === 'error') {
        assistantMessage.content = '抱歉，AI服务出现错误，请稍后再试。'
        // 强制触发响应式更新
        messages.splice(0, messages.length, ...messages)
        ElMessage.error(chunk.message)
        nextTick(() => scrollToBottom())
      }
    },
    (fullResponse) => {
      loading.value = true
      // 流式响应完成
      assistantMessage.content = fullResponse
      loading.value = false
      // 强制触发响应式更新
      messages.splice(0, messages.length, ...messages)
      nextTick(() => scrollToBottom())
    },
    (error) => {
      // 错误处理
      assistantMessage.content = '抱歉，发送消息失败，请重试。'
      loading.value = false
      // 强制触发响应式更新
      messages.splice(0, messages.length, ...messages)
      ElMessage.error(error)
      nextTick(() => scrollToBottom())
    }
  )
}

// 处理快捷操作
const handleQuickAction = async (action: QuickAction) => {
  inputMessage.value = action.title
  await sendMessage()
}

// 开始语音输入
const startVoiceInput = () => {
  ElMessage.info('语音输入功能开发中...')
}

// 滚动到底部
const scrollToBottom = () => {
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (timestamp: string) => {
  return dayjs(timestamp).format('HH:mm')
}

// 获取快捷操作
const fetchQuickActions = async () => {
  try {
    const response = await getQuickActions()
    const responseData = response.data as any
    quickActions.value = responseData.data
  } catch (error) {
    console.error('获取快捷操作失败:', error)
  }
}

// 页面挂载时执行
onMounted(() => {
  // fetchUnreadCount()
  fetchQuickActions()
  
  // 添加欢迎消息
  messages.push({
    id: 'welcome',
    type: 'assistant',
    content: '您好！我是音乐节智能助手，很高兴为您服务。我可以帮您查询演出信息、艺人详情、场地导航等。请问有什么可以帮您的吗？',
    timestamp: new Date().toISOString()
  })
})
</script>

<style lang="scss" scoped>
.home-container {
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.chat-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.05)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
    opacity: 0.3;
    pointer-events: none;
  }
}

.chat-header {
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  padding: 15px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  z-index: 10;
  flex-shrink: 0;
}

.back-btn {
  background: transparent;
  border: none;
  color: white;
  
  &:hover {
    background: transparent;
  }
}

.back-icon {
  width: 20px;
  height: 20px;
  object-fit: contain;
  filter: brightness(0) invert(1);
  display: block;
  flex-shrink: 0;
}

.chat-title {
  color: white;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  flex: 1;
  text-align: center;
}

.menu-btn {
  background: transparent;
  border: none;
  color: white;
  
  &:hover {
    background: transparent;
  }
}

.menu-icon {
  width: 20px;
  height: 20px;
  object-fit: contain;
  filter: brightness(0) invert(1);
  display: block;
  flex-shrink: 0;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  position: relative;
}

.message {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
  
  &.user {
    flex-direction: row-reverse;
    
    .message-content {
      align-items: flex-end;
    }
    
    .message-bubble {
      background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
      color: white;
      border-radius: 18px 18px 4px 18px;
    }
  }
  
  &.assistant {
    .message-bubble {
      background: rgba(255, 255, 255, 0.1);
      color: white;
      border-radius: 18px 18px 18px 4px;
      backdrop-filter: blur(10px);
    }
  }
}

.message-avatar {
  margin: 0 12px;
  flex-shrink: 0;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.message-bubble {
  padding: 12px 16px;
  font-size: 14px;
  line-height: 1.4;
  word-wrap: break-word;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  &.loading {
    background: rgba(255, 255, 255, 0.1);
    color: white;
  }
}

.loading-dots {
  display: flex;
  gap: 4px;
  
  span {
    width: 6px;
    height: 6px;
    background: white;
    border-radius: 50%;
    animation: loading 1.4s infinite ease-in-out;
    
    &:nth-child(1) { animation-delay: -0.32s; }
    &:nth-child(2) { animation-delay: -0.16s; }
  }
}

@keyframes loading {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.message-time {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.5);
  margin-top: 4px;
  text-align: center;
}



.input-section {
  padding: 15px 20px;
  background: rgba(0, 0, 0, 0.8);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  flex-shrink: 0;
}

.input-container {
  display: flex;
  gap: 0px;
  align-items: center;
}

.message-input {
  flex: 1;
  
  :deep(.el-input__wrapper) {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 25px;
    backdrop-filter: blur(10px);
    
    &:hover {
      border-color: rgba(255, 255, 255, 0.3);
    }
    
    &.is-focus {
      border-color: #4CAF50;
      box-shadow: 0 0 0 1px rgba(76, 175, 80, 0.2);
    }
  }
  
  :deep(.el-input__inner) {
    color: white;
    
    &::placeholder {
      color: rgba(255, 255, 255, 0.6);
    }
  }
  
  :deep(.el-input-group__append) {
    background: transparent;
    border: none;
    box-shadow: none;
  }
}

.voice-btn {
  background: transparent;
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: none;
  transition: all 0.3s ease;
  padding: 0;
  min-height: 40px;
  
  &:hover {
    background: transparent;
    transform: scale(1.05);
  }
}

.voice-icon {
  width: 28px;
  height: 28px;
  object-fit: contain;
  filter: brightness(0) invert(1);
  display: block;
  flex-shrink: 0;
}

.send-btn {
  background: transparent;
  color: white;
  border: none;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: none;
  transition: all 0.3s ease;
  
  &:hover {
    background: transparent;
    transform: scale(1.05);
  }
  
  &:disabled {
    background: transparent;
    color: rgba(255, 255, 255, 0.5);
    cursor: not-allowed;
    transform: none;
  }
}

.send-icon {
  width: 20px;
  height: 20px;
  filter: brightness(0) invert(1);
}

.floating-quick-actions {
  position: fixed;
  bottom: 100px;
  left: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  z-index: 100;
}

.quick-action-item {
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  border: none;
  border-radius: 20px;
  padding: 8px 12px;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  backdrop-filter: blur(10px);
  
  &:hover {
    background: white;
    transform: translateX(3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

.quick-action-text {
  white-space: nowrap;
  display: block;
}

.floating-features {
  position: fixed;
  bottom: 100px;
  right: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  z-index: 100;
}

.floating-feature-btn {
  position: relative;
  border-radius: 50%;
  width: 70px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-3px);
    filter: brightness(1.1);
  }
  
  &:active {
    transform: translateY(-1px);
  }
}

.feature-img {
  width: 40px;
  height: 40px;
  object-fit: contain;
  transform: translateY(35px);
  z-index: 0;
}

.feature-icon-above {
  position: absolute;
  top: 0;
  width: 55px;
  height: 55px;
  object-fit: contain;
  z-index: 2;
}

// 移动端适配
@media screen and (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  
  .chat-section {
    flex: 1;
    min-height: 0;
  }
  
  .floating-quick-actions {
    bottom: 95px;
    left: 15px;
    gap: 8px;
  }
  
  .quick-action-item {
    padding: 6px 10px;
    font-size: 11px;
  }
  
  .floating-features {
    bottom: 95px;
    right: 15px;
    gap: 12px;
  }
  
  .floating-feature-btn {
    width: 60px;
    height: 60px;
  }
  
  .feature-img {
    width: 32px;
    height: 32px;
    transform: translateY(25px);
  }
  
  .feature-icon-above {
    top: 0;
    width: 42px;
    height: 42px;
  }
  
  .menu-icon,
  .voice-icon,
  .send-icon,
  .back-icon {
    width: 26px;
    height: 26px;
    object-fit: contain;
  }
}
</style> 